package www.lagou.dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import www.lagou.entity.account;
import www.lagou.entity.transaction;
import www.lagou.utils.DruidUtils;

import java.sql.SQLException;

public class accountDao {
    /**
     * 判断转出方余额是否有足够的金额
     *
     */

    public boolean isEnoughMoney(String card) throws SQLException {
        //获取QueryRunner对象
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

        //编写SQL
        String sql = "select balance from account where card = ?";

        //执行查询,采用BeanHandle来封装结果，获取结果集中的第一条数据
        account account = qr.query(sql, new BeanHandler<account>(account.class), card);
        double balance = account.getBalance();

        if(balance>5000){
            System.out.println("有足够的余额！");
            return true;
        }else{
            System.out.println("余额不足！");
            return false;
        }

    }

    public boolean delTransaction(String card) throws SQLException {
        //获取QueryRunner对象
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
        //执行卡的扣除操作
        String sql = "update account set balance = balance - 5000 where card = ?";


        int update = 0;
        if(isEnoughMoney(card)){
            update = qr.update(sql, card);

        }
        if(update>0){
            System.out.println("转出成功！");
            return true;
        }else{
            System.out.println("转出失败");
            return false;
        }
    }
    public boolean insTransaction(String card) throws SQLException {
        //获取QueryRunner对象
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
        //执行卡的增加操作
        String sql = "update account set balance = balance + 5000 where card = ?";


         int account = qr.update(sql,card);

        if(account>0){
            System.out.println("转入成功!");
            return true;
        }else{
            System.out.println("转入失败！");
            return false;
        }
    }

    public account getAccount(String card) throws SQLException {
        //获取QueryRunner对象
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

        String sql = "select * from account where card = ?";

        account account = qr.query(sql, new BeanHandler<account>(account.class), card);

        return account;
    }
    public boolean insertData(transaction t1) throws SQLException {
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

        String sql = "insert into transaction values(?,?,?,?,?)";

        Object[] params = {t1.getId(),t1.getCardid(),t1.getTratype(),t1.getTramoney(),t1.getDATETIME()};

        int update = qr.update(sql, params);

        if(update>0){
            System.out.println("插入成功！");
            return true;
        }else{
            System.out.println("插入失败！");
            return false;
        }
    }
}
